package com.pz.home;

import dbtools.DataSimpDto;

import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.fop.svg.PDFTranscoder;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.dao.IGenericBaseCommonDao;
import org.jeecgframework.core.common.model.json.Highchart;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.system.service.LogService;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/homeController")
public class homeController extends BaseController {
    private SystemService systemService;



    @Autowired
    public void setSystemService(SystemService systemService) {
        this.systemService = systemService;
    }



    /**
     * 数据传输分析
     *
     * @return
     */
    @RequestMapping(params = "datachanshu")
    public ModelAndView fxBroswer(String reportType, HttpServletRequest request) {
        request.setAttribute("reportType", reportType);
        if("pie".equals(reportType)){
           // return new ModelAndView("system/log/userBroswerPie");
        }else if("line".equals(reportType)) {
        }
        return new ModelAndView("home/"+reportType);
    }
    /**
     * 报表数据生成
     *
     * @return
     */
    @RequestMapping(params = "getBroswerBar")
    @ResponseBody
    public List<Highchart> getBroswerBar(HttpServletRequest request, String reportType, HttpServletResponse response) {
    	// 获取当前登录用户
    			String fd_lrr = ResourceUtil.getUserSystemData("sysUserCode");
    	List<Highchart> list = new ArrayList<Highchart>();
        Highchart hc = new Highchart();
        StringBuffer sb = new StringBuffer();
       /* sb.append("SELECT broswer ,count(broswer) FROM TSLog group by broswer");*/
        DataSimpDto b=new DataSimpDto();
        if (fd_lrr.equals("admin")) {
        	sb.append("SELECT	DATE_FORMAT(fd_uptime, '%y-%m-%d') broswer,	count(*) FROM	t_log_upproc WHERE	fd_dstat LIKE '%成功%' and fd_dtype='FTP'  GROUP BY	DATE_FORMAT(fd_uptime, '%y-%m-%d') ORDER BY	fd_uptime desc LIMIT 10");
        	b=new DataSimpDto("SELECT COUNT(1) FROM t_log_upproc WHERE fd_dtype='FTP'");
		} else {
			switch (Integer.parseInt(fd_lrr)) {
			case 18:
				fd_lrr = "1890煤矿";
				break;
			case 19:
				fd_lrr = "1930煤矿";
				break;
			case 21:
				fd_lrr = "2130煤矿";
				break;
				}
				sb.append("SELECT	DATE_FORMAT(fd_uptime, '%y-%m-%d') broswer,	count(*) FROM	t_log_upproc WHERE	fd_dstat LIKE '%成功%' and fd_dtype='FTP' and fd_fwno='"+fd_lrr+"'  GROUP BY	DATE_FORMAT(fd_uptime, '%y-%m-%d') ORDER BY	fd_uptime desc LIMIT 10");
	        	b=new DataSimpDto("SELECT COUNT(1) FROM t_log_upproc WHERE fd_dtype='FTP' and  fd_fwno='"+fd_lrr+"'" );
		}
        DataSimpDto a=new DataSimpDto(sb.toString());
        int count = Integer.parseInt(b.getDataValue(0,0));
        List lt = new ArrayList();
        hc = new Highchart();
     //   hc.setName(MutiLangUtil.getMutiLangInstance().getLang(USER_BROWSER_ANALYSIS));
        hc.setType(reportType);
        Map<String, Object> map;
        if (a.getTotRecord()> 0) {
            for (int i=0;i<a.getTotRecord();i++) {
                map = new HashMap<String, Object>();

                map.put("name", a.getDataValue(0,i));
                map.put("y",  a.getDataValue(1,i));
                int groupCount = Integer.parseInt(""+a.getDataValue(1,i));
                Double  percentage = 0.0;
                if (count != 0) {
                    percentage = new Double(groupCount)/count;
                }
            //    map.put("percentage", groupCount);
                lt.add(map);
            }
        }
        hc.setData(lt);
        list.add(hc);
        return list;
    }
    /**
     * hightchart导出图片
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(params = "export")
    public void export(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String type = request.getParameter("type");
        String svg = request.getParameter("svg");
        String filename = request.getParameter("filename");

        filename = filename == null ? "chart" : filename;
        ServletOutputStream out = response.getOutputStream();
        try {
            if (null != type && null != svg) {
                svg = svg.replaceAll(":rect", "rect");
                String ext = "";
                Transcoder t = null;
                if (type.equals("image/png")) {
                    ext = "png";
                    t = new PNGTranscoder();
                } else if (type.equals("image/jpeg")) {
                    ext = "jpg";
                    t = new JPEGTranscoder();
                } else if (type.equals("application/pdf")) {
                    ext = "pdf";
                    t = (Transcoder) new PDFTranscoder();
                } else if (type.equals("image/svg+xml"))
                    ext = "svg";
                response.addHeader("Content-Disposition",
                        "attachment; filename=" + new String(filename.getBytes("GBK"),"ISO-8859-1") + "." + ext);
                response.addHeader("Content-Type", type);

                if (null != t) {
                    TranscoderInput input = new TranscoderInput(
                            new StringReader(svg));
                    TranscoderOutput output = new TranscoderOutput(out);

                    try {
                        t.transcode(input, output);
                    } catch (TranscoderException e) {
                        out.print("Problem transcoding stream. See the web logs for more details.");
                        e.printStackTrace();
                    }
                } else if (ext.equals("svg")) {
                    // out.print(svg);
                    OutputStreamWriter writer = new OutputStreamWriter(out,
                            "UTF-8");
                    writer.append(svg);
                    writer.close();
                } else
                    out.print("Invalid type: " + type);
            } else {
                response.addHeader("Content-Type", "text/html");
                out
                        .println("Usage:\n\tParameter [svg]: The DOM Element to be converted."
                                + "\n\tParameter [type]: The destination MIME type for the elment to be transcoded.");
            }
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}
